from datetime import datetime
from plantmanagement import settings
from plantmanagement import db
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer


class Users(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    head = db.Column(db.String(200))
    nickname = db.Column(db.String(20))
    openid = db.Column(db.String(200))
    datetimes = db.Column(db.DateTime, default=datetime.now, index=True)

    def to_json(self):
        dicts = self.__dict__
        if "_sa_instance_state" in dicts:
            del dicts["_sa_instance_state"]
        return dicts

    @staticmethod
    def create_token(user_id):
        s = Serializer(settings.SECRET_KEY, expires_in=1800)
        token = s.dumps({"id": user_id}).decode('ascii')
        return token


class Record(db.Model):
    __tablename__ = 'record'
    id = db.Column(db.Integer, primary_key=True)
    plantid = db.Column(db.Integer, db.ForeignKey('plant.id'))
    userid = db.Column(db.Integer, db.ForeignKey('user.id'))
    datetimes = db.Column(db.DateTime, default=datetime.now, index=True)
    type = db.Column(db.Integer)

    def to_json(self):
        dicts = self.__dict__
        if "_sa_instance_state" in dicts:
            del dicts["_sa_instance_state"]
        return dicts


class plant(db.Model):
    __tablename__ = 'plant'
    id = db.Column(db.Integer, primary_key=True)
    plantname = db.Column(db.String(20))
    introduce = db.Column(db.String(100))
    src = db.Column(db.String(200))

    def to_json(self):
        dicts = self.__dict__
        if "_sa_instance_state" in dicts:
            del dicts["_sa_instance_state"]
        return dicts


class userplant(db.Model):
    __tablename__ = 'userplant'
    id = db.Column(db.Integer, primary_key=True)
    plantname = db.Column(db.String)
    plantsrc = db.Column(db.String)
    userid = db.Column(db.Integer)
    introduce = db.Column(db.String)

    def to_json(self):
        dicts = self.__dict__
        if "_sa_instance_state" in dicts:
            del dicts["_sa_instance_state"]
        return dicts
